from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, JsonResponse

from meiduo_mall.settings.dev import logger
from verifications.libs.captcha.captcha import captcha
from apps.verifications.libs.yuntongxun.ccp_sms import CCP
from django_redis import get_redis_connection
import random
import re
from celery_tasks.sms.tasks import ccp_send_sms_code



# from celery_tasks


# Create your views here.


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()

        conn = get_redis_connection('verify_code')
        conn.setex(
            'img_%s' % uuid,
            300,
            text
        )
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):

        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code, uuid]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            }, status=400)

        if not re.match(r'^[a-zA-Z0-9]{4}$', image_code):
            return JsonResponse({
                'code': 400,
                'errmsg': '图形验证码格式有误！'
            }, status=400)

        if not re.match(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}', uuid):
            return JsonResponse({
                'code': 400,
                'errmsg': 'uuid不符合格式'
            }, status=400)

        conn = get_redis_connection('verify_code')

        image_code_from_redis = conn.get('img_%s' % uuid)

        conn.delete('img_%s' % uuid)

        if not image_code_from_redis:
            return JsonResponse({
                'code': 400,
                'errmsg': '图形验证码过期失效！'
            }, status=403)
        #
        # try:
        #     conn.delete('img_%s' % uuid)
        #
        # except Exception as e:
        #     logger.error(e)

        image_code_from_redis = image_code_from_redis.decode()

        if image_code.lower() != image_code_from_redis.lower():
            return JsonResponse({
                'code': 400,
                'errmsg': '输入图形验证码有误'
            }, status=400)

        send_flag = conn.get("send_flag_%s" % mobile)

        if send_flag:
            return JsonResponse({
                'code': 400,
                'errmsg': '请勿重复发送'
            }, status='403')

        sms_code = '%06d' % random.randint(0, 999999)
        print('短信验证码:', sms_code)

        logger.info(sms_code)

        pl = conn.pipeline()

        pl.setex(
            'sms_%s' % mobile,
            300,
            sms_code
        )
        # conn.setex(
        #     'sms_%s' % mobile,
        #     300,
        #     sms_code
        # )
        #


        pl.setex(
            'send_flag_%s' % mobile,
            60,
            '1'
        )
        # conn.setex(
        #     'send_flag_%s' % mobile,
        #     60,
        #     '1'
        # )

        pl.execute()

        # CCP().send_template_sms(
        #     mobile,
        #     [sms_code, 5],
        #     1
        # )

        ccp_send_sms_code.delay(mobile, sms_code)

        return JsonResponse({
            'code': 0,
            'errmsg': '发送短信成功'
        })
